package com.leyou.common.advice;

import com.leyou.common.exception.LyException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Slf4j
@Aspect
@Component
public class CommonLogAdvice {

    @Around("within(@org.springframework.stereotype.Service *) || within(com.baomidou.mybatisplus.extension.service.IService+)")
    public Object handleExceptionLog(ProceedingJoinPoint jp) throws Throwable {
        try {
            log.debug("{}方法执行了, 参数{}", jp.getSignature().getName(), Arrays.toString(jp.getArgs()));
            long a = System.nanoTime();
            Object result = jp.proceed();
            log.debug("{}方法调用成功, 耗时{}", jp.getSignature().getName(), System.nanoTime() - a);
            return result;
        } catch (Throwable throwable) {
            log.error("{}方法执行失败, 原因{}", jp.getSignature().getName(), throwable.getMessage(), throwable);
            if (throwable instanceof LyException) {
                throw throwable;
            } else {
                throw  new LyException(500, throwable);
            }
        }
    }
}